package com.bric.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;


/**
 * zip压缩文件工具类
 * ClassName: ZipCompressorByAnt
 * @Description: TODO
 * @author dingpeng
 * @date 2016-4-13
 */
public class ZipCompressorByAnt {
	private static final Logger log=Logger.getLogger(ZipCompressorByAnt.class);
	/** 
	 * 压缩文件列表到某ZIP文件 
	 * @param zipFilename 要压缩到的ZIP文件 
	 * @param paths 文件列表，多参数 
	 * @throws Exception 
	 */  
	public static void compress(String zipFilename, String... paths)throws Exception {  
		compress(new FileOutputStream(zipFilename), paths);  
	}  

	/** 
	 * 压缩文件列表到输出流 
	 * @param os 要压缩到的流 
	 * @param paths 文件列表，多参数 
	 * @throws Exception 
	 */  
	public static void compress(OutputStream os, String... paths)throws Exception {  
		ZipOutputStream zos = new ZipOutputStream(os);  
		for (String path : paths) {  
			if (path.equals(""))  
				continue;  
			java.io.File file = new java.io.File(path);  
			if (file.exists()) {  
				if (file.isDirectory()) {  
					zipDirectory(zos, file.getPath(), file.getName()  
							+ File.separator);  
				} else {  
					zipFile(zos, file.getPath(), "");  
				}  
			}  
		}  
		zos.close();  
	}  

	private static void zipDirectory(ZipOutputStream zos, String dirName,String basePath) throws Exception {  
		File dir = new File(dirName);  
		if (dir.exists()) {  
			File files[] = dir.listFiles();  
			if (files.length > 0) {  
				for (File file : files) {  
					if (file.isDirectory()) {  
						zipDirectory(zos, file.getPath(), basePath  
								+ file.getName().substring(  
										file.getName().lastIndexOf(  
												File.separator) + 1)  
												+ File.separator);  
					} else  
						zipFile(zos, file.getPath(), basePath);  
				}  
			} else {  
				ZipEntry ze = new ZipEntry(basePath);  
				zos.putNextEntry(ze);  
			}  
		}  
	}  

	private static void zipFile(ZipOutputStream zos, String filename,String basePath) throws Exception {  
		File file = new File(filename);  
		if (file.exists()) {  
			FileInputStream fis = new FileInputStream(filename);  
			ZipEntry ze = new ZipEntry(basePath + file.getName());  
			zos.putNextEntry(ze);  
			byte[] buffer = new byte[8192];  
			int count = 0;  
			while ((count = fis.read(buffer)) > 0) {  
				zos.write(buffer, 0, count);  
			}  
			fis.close();  
		}  
	}
	 /** 
     * 解压缩zip包 
     * @param zipFilePath zip文件的全路径 
     * @param unzipFilePath 解压后的文件保存的路径 
     * @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含；false-不包含 
     */  
    @SuppressWarnings("unchecked")  
    public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception  
    {  
        if (null==zipFilePath||"".equals(zipFilePath)||(null==unzipFilePath||"".equals(unzipFilePath)))  
        {  
            throw new NullPointerException();            
        }  
        File zipFile = new File(zipFilePath);  
        //如果解压后的文件保存路径包含压缩文件的文件名，则追加该文件名到解压路径  
        if (includeZipFileName)  
        {  
            String fileName = zipFile.getName();  
            if (null==fileName||"".equals(fileName))  
            {  
                fileName = fileName.substring(0, fileName.lastIndexOf("."));  
            }  
//            unzipFilePath = unzipFilePath + File.separator + fileName;  
            unzipFilePath = unzipFilePath + fileName;  
        }  
        //创建解压缩文件保存的路径  
        File unzipFileDir = new File(unzipFilePath);  
        if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())  
        {  
            unzipFileDir.mkdirs();  
        }  
          
        //开始解压  
        ZipEntry entry = null;  
        String entryFilePath = null, entryDirPath = null;  
        File entryFile = null, entryDir = null;  
        int index = 0, count = 0, bufferSize = 1024;  
        byte[] buffer = new byte[bufferSize];  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
        ZipFile zip = new ZipFile(zipFile);  
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries();  
        //循环对压缩包里的每一个文件进行解压       
        while(entries.hasMoreElements())  
        {  
            entry = entries.nextElement();  
            //构建压缩包中一个文件解压后保存的文件全路径  
//            entryFilePath = unzipFilePath + File.separator + entry.getName(); 
            int ind=entry.getName().lastIndexOf("\\");
            if(ind>=0){///表示window上传的文件，需要以下转换
            	String tempPath=entry.getName().substring(0, entry.getName().lastIndexOf("\\"));
            	  log.info("解压文件的相对路径："+tempPath);
                entryDirPath=unzipFilePath+tempPath.replaceAll("\\\\", "/");
                log.info("解压文件文件夹的全路径"+entryDirPath);
              entryFilePath = unzipFilePath + entry.getName().replaceAll("\\\\", "/"); 
            }else{//linux上传文件，无需转换
            	String tempPath=entry.getName().substring(0, entry.getName().lastIndexOf("/"));
            	log.info("解压文件的相对路径："+tempPath);
            	entryDirPath=unzipFilePath+tempPath;
            	log.info("解压文件文件夹的全路径"+entryDirPath);
            	entryFilePath = unzipFilePath + entry.getName(); 
            	log.info("文件的全路径"+entryFilePath);
            }
           /* entryFilePath = unzipFilePath + entry.getName(); 
            
            entryFilePath=entryFilePath.replaceAll(File.separator, "/");
            //构建解压后保存的文件夹路径  
            index = entryFilePath.lastIndexOf("/");  
            if (index != -1)  
            {  
                entryDirPath = entryFilePath.substring(0, index);  
            }  
            else  
            {  
                entryDirPath = "";  
            }   */          
            entryDir = new File(entryDirPath);  
            //如果文件夹路径不存在，则创建文件夹  
            if (!entryDir.exists() || !entryDir.isDirectory())  
            {  
                entryDir.mkdirs();  
            }  
              
            //创建解压文件  
            entryFile = new File(entryFilePath);  
            if (entryFile.exists())  
            {  
                //检测文件是否允许删除，如果不允许删除，将会抛出SecurityException  
//                SecurityManager securityManager = new SecurityManager();  
               // SecurityManager securityManager = System.getSecurityManager();
                //securityManager.checkDelete(entryFilePath);  
                //删除已存在的目标文件  
                entryFile.delete();   
            }
              
            //写入文件  
            bos = new BufferedOutputStream(new FileOutputStream(entryFile));  
            bis = new BufferedInputStream(zip.getInputStream(entry));  
            while ((count = bis.read(buffer, 0, bufferSize)) != -1)  
            {  
                bos.write(buffer, 0, count);  
            }  
            bos.flush();  
            bos.close();              
        }  
    }  
	/*public static void main(String[] args) {
		try {
			compress("D:/a.zip","D:/fagaiwei/temp/","D:/data.txt","/usr/local/cachefile");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
}
